package com.innovation.dao;

import org.apache.log4j.Logger;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.innovation.data.model.Ids;
import com.innovation.exception.DBException;

public class IdDao extends BaseDao<Ids> {
	private static final Logger log = Logger.getLogger(IdDao.class);
	
	public int findAndModify(String table){
		final Datastore ds = getDatastore();
		return findModify(table, ds);
	}
	
	/**
	 * 通过表名获取该表数据项的最大索引,设置索引为当前索引+1
	 * @param table
	 * @param ds
	 * @return 0表示有异常,最小值为1
	 */
	public int findModify(String table, Datastore ds){
		try {
			Query<Ids> query = ds.createQuery(Ids.class).field("table").equal(table);
			if(query.asList().isEmpty()){
				Ids i = new Ids();
				int id = 0;
				i.setMaxId(id);
				i.setTable(table);
				ds.save(i);
			}
			UpdateOperations<Ids> updateOps = ds.createUpdateOperations(Ids.class);
			updateOps.inc("maxId",1);
			
			Ids ids = ds.findAndModify(query, updateOps);
			return ids.getMaxId();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new DBException(e);
		} 
	}
	
}
